package com.hitqz.robot.dispatch.netty.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.common.collect.Maps;
import com.hitqz.robot.api.business.entity.RobotEntity;
import com.hitqz.robot.api.business.entity.RobotGroupEntity;
import com.hitqz.robot.api.dispatch.protocol.dto.RobotApplyPathDto;
import com.hitqz.robot.dispatch.netty.strategy.AlgorithmStrategy;
import com.hitqz.robot.dispatch.netty.util.KcStrategyUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 科聪控制器-调度软件
 * @author xupkun
 * @date 2025/2/5
 */
@Service("kcStrategy")
@RequiredArgsConstructor
@Slf4j
public class KcDispatchService implements AlgorithmStrategy {


    /**
     * 调度系统的地址链接
     * 到时候项目不同的话进行变更
     */
    private static final String baseUrl = "http://127.0.0.1:8900/api/fms";

    /**
     * 添加移动任务
     */
    private static final String addTask = baseUrl + "/addMoveTask";
    /**
     * 取消当前任务
     */
    private static final String abortTask = baseUrl + "/abortVehicleTask";

    private static final String completeTask = baseUrl + "/completeTask";


    /**
     * 复位AGV
     */
    private static final String resetAgv = baseUrl + "/resetVehicle";


    private static final String queryTaskStatus = baseUrl + "/taskStatus";

    private final RestTemplate restTemplate;

    /**
     * 提交路径
     * @param robotGroup
     * @param pathDto
     */
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void changePath(RobotGroupEntity robotGroup, RobotApplyPathDto pathDto) {
        log.info("请求前往目标点：" + pathDto.getPathList());
        try {
            lock.lock(); // 获取锁
            String taskNo = KcStrategyUtil.ROBOT_TASK_NO.get(pathDto.getClientId());
            // 中断当前任务

            Map<String, Object> requestParams = Maps.newHashMap();
            requestParams.put("VehicleNo", pathDto.getClientId());
            String body = JSONObject.toJSONString(requestParams);
            sendDispatch(body, abortTask);

            sendDispatch(body, resetAgv);


            if (StrUtil.isNotEmpty(taskNo)) {
                // 取消任务
                // 查询当前的任务状态
                //Map<String, Object> ret = Maps.newHashMap();
                //ret.put("TaskNo", pathDto.getClientId());
                //String taskStatus = sendDispatch(JSONObject.toJSONString(ret), abortTask);
                //JSONObject taskStatusResult = JSONObject.parseObject(taskStatus);
                //if (taskStatusResult.containsKey("Status")) {
                //    String status = taskStatusResult.getString("Status");
                //    if (status.equals("running")) {
                //        Map<String, Object> requestParams = Maps.newHashMap();
                //        requestParams.put("VehicleNo", pathDto.getClientId());
                //        String body = JSONObject.toJSONString(requestParams);
                //        sendDispatch(body, abortTask);
                //        while (true) {
                //            taskStatusResult = JSONObject.parseObject(taskStatus);
                //            status = taskStatusResult.getString("Status");
                //            if (!status.equals("running")) {
                //                break;
                //            }
                //        }
                //        // 复位
                //        sendDispatch(body, resetAgv);
                //    }
                //}
            }
            // 发送任务
            if (!pathDto.getPathList().isEmpty()) {
                taskNo = "hit" + System.currentTimeMillis();
                requestParams = Maps.newHashMap();
                requestParams.put("TaskNo", taskNo);
                requestParams.put("Priority", 0);
                requestParams.put("Location", pathDto.getPathList().get(pathDto.getPathList().size() - 1).getCode());
                requestParams.put("VehicleNo", pathDto.getClientId());
                requestParams.put("FinishAction", 1);
                String requestBody = JSONObject.toJSONString(requestParams);
                sendDispatch(requestBody, addTask);
                KcStrategyUtil.ROBOT_TASK_NO.put(pathDto.getClientId(), taskNo);
                log.info("执行前往点位的TaskNo：" + taskNo);
            }
        } catch (Exception e) {
            log.error("提交路径失败", e);
        } finally {
            lock.unlock(); // 释放锁
        }
    }



    /**
     * 计算路径，由于采用第三方的调度软件，无须相关具体实现，但是依然会实现
     * @param groupId
     * @param robotEntityList
     */
    @Override
    public void calculate(int groupId, List<RobotEntity> robotEntityList) {

    }


    private String sendDispatch(String requestBody, String uri) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> requestEntity = new HttpEntity<>( requestBody, headers);
            log.info("请求地址{} 参数: {}", uri
                    , requestBody);
            String response = restTemplate.postForObject(uri, requestEntity, String.class);
            log.info("调度返回接果: " + response);
            return response;
        } catch (Exception e) {
            log.info("请求地址发生异常:" + e.getMessage());
        }
        return null;
    }


}
